<template>
  <el-row class="my-15px">
    <el-col :span="22" :offset="1">
      <div class="mb-15px" v-if="!isDisabled">
        <el-button type="primary" @click="addProduct">添加产品</el-button>
        <el-button @click="addSupplier">添加供应商</el-button>
      </div>
      <div>
        <el-row class="tableHeader">
          <el-col :span="2" v-if="!isDisabled"
            ><el-checkbox v-model="checkAll"></el-checkbox
          ></el-col>
          <el-col :span="!isDisabled ? 10 : 12">产品型号</el-col>
          <el-col :span="!isDisabled ? 10 : 12">数量</el-col>
          <el-col :span="2" v-if="!isDisabled">操作</el-col>
        </el-row>
        <el-row class="tableEmpty" v-if="!tableData.length"> 暂无数据 </el-row>
        <el-row
          v-for="(item, index) in tableData"
          :key="index"
          class="tableRow"
        >
          <el-col :span="2" v-if="!isDisabled">
            <el-checkbox v-model="item.checked"></el-checkbox>
          </el-col>
          <el-col :span="!isDisabled ? 10 : 12">
            <el-input
              v-model="item.productModel"
              placeholder="请输入产品型号"
              :disabled="isDisabled"
              @change="checkRepeat"
            ></el-input>
          </el-col>
          <el-col :span="!isDisabled ? 10 : 12">
            <el-input
              v-model="item.productNum"
              placeholder="请输入数量"
              :disabled="isDisabled"
            ></el-input
          ></el-col>
          <el-col :span="2" v-if="!isDisabled">
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(index, tableData)"
              >删除</el-button
            >
          </el-col>
          <el-row
            style="width: 100%"
            v-if="item.extVoList.length"
            class="childHeader"
          >
            <el-col :offset="2" :span="3">供应商</el-col>
            <el-col :span="4">产品配置</el-col>
            <el-col :span="2">产品单价(元)</el-col>
            <el-col :span="2">产品税率(%)</el-col>
            <el-col :span="3">产品总价(元)</el-col>
            <el-col :span="isDisabled ? 4 : 3">供应商征信分</el-col>
            <el-col :span="isDisabled ? 4 : 3">征信分相关附件</el-col>
            <el-col :span="2" v-if="!isDisabled">操作</el-col>
          </el-row>
          <el-row
            v-for="(m, n) in item.extVoList"
            :key="n"
            style="width: 100%"
            class="childRow"
          >
            <el-col :offset="2" :span="3">
              <el-input
                type="textarea"
                rows="3"
                v-model="item.extVoList[n].brand"
                :disabled="isDisabled"
                @change="updateBrandInfo"
              ></el-input
            ></el-col>
            <el-col :span="4">
              <el-input
                type="textarea"
                rows="3"
                v-model="item.extVoList[n].configuration"
                :disabled="isDisabled"
                maxlength="400"
                show-word-limit
                @change="updateBrandInfo"
              ></el-input
            ></el-col>
            <el-col :span="2">
              <el-input
                v-model="item.extVoList[n].quotation"
                :disabled="isDisabled"
                @change="updateBrandInfo"
              ></el-input
            ></el-col>
            <el-col :span="2">
              <el-input
                v-model="item.extVoList[n].tax"
                :disabled="isDisabled"
                @change="updateBrandInfo"
              ></el-input
            ></el-col>
            <el-col :span="3">
              <el-input
                :value="
                  CalcRowPrice(item.extVoList[n].quotation, item.productNum)
                "
                disabled
              ></el-input
            ></el-col>
            <el-col :span="isDisabled ? 4 : 3">
              <el-input
                type="textarea"
                rows="3"
                v-model="item.extVoList[n].credit"
                :disabled="isDisabled"
                @change="updateBrandInfo"
              ></el-input
            ></el-col>
            <el-col :span="isDisabled ? 4 : 3">
              <el-upload
                class="upload-demo"
                action="#"
                :http-request="
                  parmas => handleFileChange(parmas, item.extVoList[n].file)
                "
                accept=""
                :show-file-list="false"
                v-if="!item.extVoList[n].file?.length"
              >
                <el-button
                  type="default"
                  class="mt-10px"
                  :disabled="isDisabled"
                  style="font-size: 14px"
                  ><el-icon><UploadFilled /></el-icon>上传文件</el-button
                >
              </el-upload>
              <div
                class="text-14px mt-10px flex justify-ceneter items-center"
                style="width: 100%"
                v-else
              >
                <div v-for="(v, i) in item.extVoList[n].file" :key="v.fileId">
                  <a :href="v.url" target="_blank" class="text-#409eff">{{
                    v.origFileName
                  }}</a>
                  <el-button
                    text
                    plain
                    @click="delFileName(i, item.extVoList[n].file)"
                    v-if="!isDisabled"
                    >删除</el-button
                  >
                </div>
              </div></el-col
            >
            <el-col :span="2" v-if="!isDisabled"
              ><el-button
                size="small"
                type="warning"
                @click="deleteRow(n, item.extVoList)"
                >删除</el-button
              ></el-col
            >
          </el-row>
        </el-row>
      </div>
    </el-col>
  </el-row>
</template>

<script setup>
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
const { proxy } = getCurrentInstance()
const tableData = ref([])

const emit = defineEmits(['updateTableList'])
const prop = defineProps({
  details: {
    type: Array,
    default: () => []
  },
  isDisabled: {
    type: Boolean,
    default: false
  },
  pageType: {
    type: String,
    default: 'add'
  }
})

watch(
  () => prop.details,
  val => {
    if (prop.pageType !== 'add') {
      tableData.value = val.map(v => {
        v.extVoList = v.extVoList.map(n => {
          n.file = n.sysAttachFiles
          return n
        })
        return v
      })
    }
  }
  // { deep: true }
)

const checkAll = ref(false)
watch(checkAll, val => {
  if (val) {
    tableData.value.forEach(v => {
      v.checked = true
    })
  } else {
    tableData.value.forEach(v => {
      v.checked = false
    })
  }
})
// 添加产品
function addProduct() {
  const addRow = {
    productModel: '',
    productNum: '',
    extVoList: [
      {
        brand: '',
        configuration: '',
        quotation: '',
        tax: '',
        credit: '',
        file: []
      }
    ],
    checked: checkAll.value ? true : false
  }

  tableData.value.push(addRow)
  emit('updateTableList')
}

// 计算单行产品总价
function CalcRowPrice(num, quotation) {
  return (num * quotation).toFixed(2)
}

function updateBrandInfo() {
  emit('updateTableList')
}

// 添加供应商
function addSupplier() {
  const selectProduct = tableData.value.filter(v => v.checked)
  console.log(selectProduct)
  if (!selectProduct.length) {
    proxy.$modal.msgWarning('请选择一个产品')
    return
  }

  selectProduct.forEach(v => {
    v.extVoList.push({
      brand: '',
      configuration: '',
      quotation: '',
      tax: '',
      credit: '',
      file: []
    })
  })

  emit('updateTableList')
}

// 删除产品
function handleDelete(index, row) {
  proxy.$modal.confirm('是否确认删除该产品信息？').then(function () {
    row.splice(index, 1)
    emit('updateTableList')
  })
}

// 删除供应商
function deleteRow(index, row) {
  proxy.$modal.confirm('是否确认删除该供应商信息？').then(function () {
    row.splice(index, 1)
    emit('updateTableList')
  })
}
/**
 * 产品类型判重
 * 供应商判重
 * 格式校验
 * 必填校验
 */
function checkData() {
  if (!tableData.value.length) {
    proxy.$modal.msgError('请填写产品信息')
    return
  }
  const map = new Map()
  for (let index = 0; index < tableData.value.length; index++) {
    const element = tableData.value[index]
    if (!element.productModel) {
      proxy.$modal.msgError('产品类型不能为空')
      return false
    }
    if (!element.productNum) {
      proxy.$modal.msgError('产品数量不能为空')
      return false
    }
    if (!element.extVoList.length) {
      proxy.$modal.msgError('供应商信息不能为空')
      return false
    }
    if (map.get(element.productModel)) {
      proxy.$modal.msgError('当前存在重复产品类型，请重新输入')
      return false
    } else {
      map.set(element.productModel, element)
    }
  }

  const brandList = map.keys()
  const brandMap = new Map()
  const reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/
  for (const it of brandList) {
    console.log(it)
    const brand = map.get(it)
    for (let index = 0; index < brand.extVoList.length; index++) {
      const el = brand.extVoList[index]
      if (!el.brand) {
        proxy.$modal.msgError(brand.productModel + '供应商不能为空')
        return false
      }
      if (!el.configuration) {
        proxy.$modal.msgError(brand.productModel + '产品配置不能为空')
        return false
      }
      if (!el.quotation) {
        proxy.$modal.msgError(brand.productModel + '产品单价不能为空')
        return false
      } else {
        if (!reg.test(el.quotation)) {
          proxy.$modal.msgError(
            brand.productModel + '产品单价格式不正确,请输入至多两位小数的数字'
          )
          return false
        }
      }
      if (!el.tax) {
        proxy.$modal.msgError(brand.productModel + '产品税率不能为空')
        return false
      } else {
        if (!reg.test(el.tax)) {
          proxy.$modal.msgError(
            brand.productModel + '产品税率格式不正确,请输入至多两位小数的数字'
          )
          return false
        }
      }
      if (!el.credit) {
        proxy.$modal.msgError(el.brand + '征信分不能为空')
        return false
      }

      console.log(brandMap, 'brandMap')
      if (brandMap.get(it + el.brand)) {
        proxy.$modal.msgError('当前存在重复供应商，请重新输入')
        return false
      } else {
        brandMap.set(it + el.brand, el)
      }
    }
  }

  return true
}

// 附件上传
const fileList = ref([])

function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
  return true
}

async function handleFileChange(params, row) {
  const checkResult = beforeAvatarUpload(params.file)
  if (!checkResult) return
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      row.push(res.data)
    }
  } catch (error) {}
}

async function delFileName(index, row) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      // const file = fileList.value[index]
      const res = await delFile(row[0].fileName)
      if (res.code === 200) {
        row.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {}
}

function checkRepeat() {
  const map = new Map()
  for (let index = 0; index < tableData.value.length; index++) {
    const element = tableData.value[index]
    if (map.get(element.productModel)) {
      proxy.$modal.msgError('当前存在重复产品类型，请重新输入')
    } else {
      map.set(element.productModel, element)
      updateBrandInfo()
    }
  }
}

defineExpose({
  tableData,
  checkData
})
</script>

<style scoped lang="scss">
.tableHeader {
  border-radius: 4px;
  // margin-bottom: 10px;
  .el-col {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    // font-weight: 500;
    font-weight: bold;
    color: #57585d;
    line-height: 23px;
    height: 40px;
    // padding: 8px 0;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-bottom: none;
  }
}
.tableEmpty {
  border: 1px solid #e4e7ed;
  line-height: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #909399;
  font-size: 14px;
}

.tableRow {
  & > .el-col {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: bold;
    line-height: 23px;
    height: 50px;
    padding: 8px;
    border: 1px solid #eeeff5;
  }
}
.childHeader,
.childRow {
  .el-col {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: bold;
    color: #57585d;
    line-height: 23px;
    height: 50px;
    padding: 8px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-top: none;
  }
}
.childRow {
  .el-col {
    background-color: white;
    height: auto;
  }
}
</style>
